package org.kwisatz.proxybot.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.kwisatz.proxybot.Main;
import org.kwisatz.proxybot.Message;

public class Parser
{
	private final static String P_NICK="([^!@\\s]+)";
	private final static String P_USER="(?:!([^!@\\s]+))";
	private final static String P_SERVER="(?:@([^!@\\s]+))";
	private final static String P_PREFIX="(?::"+P_NICK+P_USER+ '?' +P_SERVER+"? +)";
	private final static String P_CMD="(\\S+)";
	private final static String P_CMDPARAM="((?: +[^\\s:]\\S*)*)";
	private final static String P_END="(?::(.*))?";
	//public final static String P_MESSAGE="^"+P_PREFIX+"?"+P_CMD+P_CMDPARAM+" *"+P_END+"$";
	public final static String P_MESSAGE= '^' +P_PREFIX+ '?' +P_CMD+P_CMDPARAM+" *:?";
	private final static Pattern PATTERN=Pattern.compile(P_MESSAGE);
	
	public static Message parse(String line)
	{
		Matcher m = PATTERN.matcher(line);
		//if(m.matches())
		if(m.lookingAt())
		{
			String nick = m.group(1);
			String user = m.group(2);
			String server = m.group(3);
			String command = m.group(4);
			String cmdParam = m.group(5).trim();
			//String msgEnd = m.group(6);
			String msgEnd = line.substring(m.end());
			return new Message(nick, user, server, command, cmdParam, msgEnd);
		}
		else
		{
			Main.LOGGER.severe(PATTERN.toString());
			Main.LOGGER.severe("Cannot parse this line: "+line);
		}
		return null;
	}
}
